import React, { Component } from 'react'
import { Layout, Button, messages } from 'antd';
const { Content } = Layout;
const constraints = window.constraints = {
    //启用音频
    audio: true,

    //禁用视频
    video: false
}
let audioTracks = {}
export default class P2_open_microphone extends Component {
    openMicroPhone = () => {
        navigator.mediaDevices.getUserMedia(constraints).then(
            this.handleSuccess
        ).catch(
            this.handleError
        );
    }
    closeMicroPhone = () => {
        const audio = this.refs['audio'];
        audio.srcObject = null
        audioTracks[0].stop();
    }
    handleSuccess = (stream) => {
        let audio = this.refs['audio']
        audioTracks = stream.getAudioTracks();
        console.log('获取到的音频设备:' + audioTracks[0].label);
        stream.oninactive = () => {
            console.log('Stream停止')
        }
        window.stream = stream;;
        audio.srcObject = stream
    }
    handleError = (error) => {
        console.log('getUserMedia error: ' + error.message, error.name)
    }

    render() {
        return (
            <div>
                <Content
                    className="site-layout-background"
                    style={{
                        padding: 24,
                        margin: 0,
                        minHeight: 700,
                    }}>
                    <audio ref="audio" controls autoPlay></audio><br /><br />
                    <Button onClick={this.openMicroPhone}>打开麦克风</Button>
                    <Button onClick={this.closeMicroPhone}>关闭麦克风</Button>
                </Content>
            </div>
        )
    }
}
